package com.jeesite.modules.common.service;

import com.jeesite.common.entity.Extend;
import com.jeesite.common.idgen.IdGen;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.modules.common.dao.SysExtractDao;
import com.jeesite.modules.common.entity.SysOrgExtract;
import com.jeesite.modules.common.entity.SysUserExtract;
import com.jeesite.modules.sys.dao.EmployeeOfficeDao;
import com.jeesite.modules.sys.dao.UserRoleDao;
import com.jeesite.modules.sys.entity.*;
import com.jeesite.modules.sys.service.EmployeeService;
import com.jeesite.modules.sys.service.OfficeService;
import com.jeesite.modules.sys.service.UserService;
import com.jeesite.modules.yzw.constant.Constant;
import com.jeesite.modules.yzw.dao.OtsDataDao;
import com.jeesite.modules.yzw.dao.OtsIflytekOrgDao;
import com.jeesite.modules.yzw.entity.OtsIflytekOrg;
import com.jeesite.modules.yzw.entity.OtsIflytekOrgUser;
import com.jeesite.modules.yzw.entity.OtsIflytekUser;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @description:
 * @author: ciye
 * @date: 2022/3/4 10:28
 */
@Service
@RequiredArgsConstructor
public class SysExtractService {
    @Resource
    private SysExtractDao sysExtractDao;
    @Autowired
    private OfficeService officeService;
    @Autowired
    private OtsDataDao otsDataDao;

    @Resource
    private UserRoleDao userRoleDao;
    @Autowired
    private UserService userService;
    @Autowired
    private EmployeeService employeeService;
    @Autowired
    private EmployeeOfficeDao employeeOfficeDao;

    @Transactional(rollbackFor = Exception.class)
    public String extractOrgInfo() {
        // 返回状态值
        String resultCode = "";
        // 计数器
        int count = 0;
        // 执行时间
        Date date = new Date();

        try {
            // 获取数据库中的机构数据
            List<SysOrgExtract> allOrgList = sysExtractDao.getAllOrgList();

            // 循环插入
            for (SysOrgExtract sysOrgExtract : allOrgList) {
                Office office = new Office();
                // 机构id
                office.setViewCode(sysOrgExtract.getOrgId());
                // 机构父id
                if (sysOrgExtract.getOrgParentId() == null) {
                    office.setParentCode("0");
                } else {
                    office.setParentCode(sysOrgExtract.getOrgParentId());
                }
                // 机构编码，附加字段
                Extend extend = new Extend();
                if (sysOrgExtract.getOrgCode() == null) {
                    // 处理测试机构的编码
                    extend.setExtendS1("test" + count);
                } else {
                    extend.setExtendS1(sysOrgExtract.getOrgCode());
                }
                // 记录和讯飞系统的关联id
                extend.setExtendS2(sysOrgExtract.getRelationId());
                office.setExtend(extend);
                // 机构简称
                office.setOfficeName(sysOrgExtract.getOrgName());
                // 机构全称
                office.setFullName(sysOrgExtract.getOrgFullName());
                // 排序号
                office.setTreeSort(sysOrgExtract.getTreeSort());

                // 机构类型
                if (sysOrgExtract.getOrgType() == null) {
                    office.setOfficeType("0");
                } else {
                    office.setOfficeType(sysOrgExtract.getOrgType());
                }
                // 机构状态，1正常，需要转换
                if ("1".equals(sysOrgExtract.getOrgStatus())) {
                    office.setStatus("0");
                } else {
                    // 设置为停用
                    office.setStatus("2");
                }
                // 创建人
                office.setCreateBy("system");
                // 创建时间
                office.setCreateDate(date);
                officeService.save(office);
                count++;
                System.out.println("已更新" + count + "条数据");
            }
            System.out.println("总共更新" + count + "条数据");
            resultCode = "success";
        } catch (Exception e) {
            e.printStackTrace();
            resultCode = "error";
        }
        return resultCode;
    }

    @Transactional(rollbackFor = Exception.class)
    public String extractUserInfo() {
        // 返回状态值
        String resultCode = "";
        // 计数器
        int count = 0;
        // 执行时间
        Date date = new Date();

        try {
            // 获取数据库中的机构数据
            List<SysOrgExtract> allOrgList = sysExtractDao.getAllOrgList();
            // 获取数据库中的用户数据
            List<SysUserExtract> allUserList = sysExtractDao.getAllUserList();

//            // 测试，只插入1000条数据
//            List<SysUserExtract> allUserListTemp = new ArrayList<>();
//            int tempSize = allUserList.size() > 1000 ? 1000 : allUserList.size() - 1;
//            if (tempSize > 0) {
//                for (int j = 0; j < tempSize; j++) {
//                    allUserListTemp.add(allUserList.get(j));
//                }
//            }

            // 循环插入
            for (SysUserExtract sysUserExtract : allUserList) {
                User user = new User();
                // 用户id
                user.setUserCode(sysUserExtract.getUserId());
                // 用户登录id
                user.setLoginCode(sysUserExtract.getPhone());
                // 用户名称
                user.setUserName(sysUserExtract.getUserName());
                // 用户类型引用编号、名称
                user.setRefCode(sysUserExtract.getUserId());
                user.setRefName(sysUserExtract.getUserName());
                // 手机号
                user.setMobile(sysUserExtract.getPhone());
                // 性别
                user.setSex(sysUserExtract.getSex());
                // 排序
                user.setUserWeight(sysUserExtract.getSeqno());
                // 职位
                Extend extend = new Extend();
                extend.setExtendS1(sysUserExtract.getPostName());
                // 和讯飞系统的关联id
                extend.setExtendS2(sysUserExtract.getRelationId());
                user.setExtend(extend);
                // 用户类型
                user.setUserType("employee");
                // 用户状态
                if ("1".equals(sysUserExtract.getUserStatus())) {
                    // 正常状态
                    user.setStatus("0");
                } else {
                    // 没有状态的默认为停用
                    user.setStatus("2");
                }
                // 备注
                user.setRemarks(sysUserExtract.getRemarks());

                // 管理员类型
                user.setMgrType("0");
                // 用户密码，初始密码
                user.setPassword("Lehand159");
                // 创建人
                user.setCreateBy("system");
                user.setCreateDate(date);

                // 插入用户机构
                Employee employee = new Employee();
                // 用户编号
                employee.setEmpCode(sysUserExtract.getUserId());
                // 用户名称
                employee.setEmpName(sysUserExtract.getUserName());

                // 插入机构
                if (sysUserExtract.getOrgIds() != null) {
                    String[] orgIds = sysUserExtract.getOrgIds().split(",");
                    String[] orgNames = sysUserExtract.getOrgNames().split(",");
                    List<String> tempOrgIds = new ArrayList<>();
                    int tempIndex = 0;
                    for (int i = 0; i < orgIds.length; i++) {
                        // 过滤重复数据
                        if (!tempOrgIds.contains(orgIds[i])) {
                            if (tempIndex == 0) {
                                // 第一次进入，作为所属机构
                                Office office = new Office();
                                // 用户机构id
                                office.setOfficeCode(orgIds[i]);
                                // 用户机构名称
                                office.setOfficeName(orgNames[i]);
                                employee.setOffice(office);
                                employee.setStatus("0");
                                tempIndex++;
                            } else {
                                // 第二次进入，作为附属机构
                                List<EmployeeOffice> employeeOfficeList = employee.getEmployeeOfficeList();
                                EmployeeOffice employeeOffice = new EmployeeOffice();
                                employeeOffice.setOfficeCode(orgIds[i]);
                                // 机构名称超长会截断，造成下标越界
                                if (i >= orgNames.length) {
                                    for (SysOrgExtract item : allOrgList) {
                                        if (StringUtils.equals(orgIds[i], item.getOrgId())) {
                                            employeeOffice.setOfficeName(item.getOrgName());
                                        }
                                    }
                                } else {
                                    employeeOffice.setOfficeName(orgNames[i]);
                                }
                                employeeOfficeList.add(employeeOffice);
                            }
                            tempOrgIds.add(orgIds[i]);
                        }
                    }

                    // 保存数据
                    userService.insert(user);
                    employeeService.insert(employee);

                    // 保存附属机构
                    if (employee.getEmployeeOfficeList().size() > 0) {
                        EmployeeOffice employeeOfficeWhere = new EmployeeOffice();
                        employeeOfficeWhere.setEmpCode(employee.getEmpCode());
                        employeeOfficeDao.deleteByEntity(employeeOfficeWhere);
                        employee.getEmployeeOfficeList().forEach(employeeOffice -> {
                            employeeOffice.setId(IdGen.nextId());
                            employeeOffice.setEmpCode(employee.getEmpCode());
                        });
                        employeeOfficeDao.insertBatch(employee.getEmployeeOfficeList());
                    }

                    // 插入角色
                    if (sysUserExtract.getRoleCodes() != null) {
                        String[] roleCodes = sysUserExtract.getRoleCodes().split(",");
                        List<String> tempRoleCodes = new ArrayList<>();
                        for (String roleCode : roleCodes) {
                            // 过滤重复数据
                            if (!tempRoleCodes.contains(roleCode)) {
                                UserRole userRole = new UserRole();
                                userRole.setUserCode(sysUserExtract.getUserId());
                                userRole.setRoleCode(roleCode);
                                userRoleDao.insert(userRole);
                                tempRoleCodes.add(roleCode);
                            }
                        }
                    }
                    count++;
                }
            }
            System.out.println("总共更新" + count + "条数据");
            resultCode = "success";
        } catch (Exception e) {
            e.printStackTrace();
            resultCode = "error";
        }
        return resultCode;
    }

    @Transactional(rollbackFor = Exception.class)
    public String resetAllPwd() {
        // 返回状态值
        String resultCode = "";
        // 计数器
        int count = 0;

        try {
            // 获取用户数据
            List<User> list = userService.findList(new User());
            for (User user : list) {
                if ("system".equals(user.getUserCode()) || "admin".equals(user.getUserCode())) {
                    continue;
                }
                userService.updatePassword(user.getUserCode(), null);
                count++;
            }
            System.out.println("总共更新" + count + "条数据");
            resultCode = "success";
        } catch (Exception e) {
            e.printStackTrace();
            resultCode = "error";
        }

        return resultCode;
    }
    @Transactional(rollbackFor = Exception.class)
    public String findOtsIflytekOrg() {
        String msg="ok";
        try {
            List<OtsIflytekOrg> otsIflytekOrgList=sysExtractDao.findOtsIflytekOrg();
            for (OtsIflytekOrg otsIflytekOrg:otsIflytekOrgList) {
                OtsIflytekOrg org=sysExtractDao.getOtsIflytekOrgById(otsIflytekOrg.getParentid());
                if(org!=null){
                    otsIflytekOrg.setWhdcpid(String.valueOf(org.getUrcorgid()));
                }else {
                    otsIflytekOrg.setWhdcpid("0");
                }
                otsDataDao.insertOtsIflytekOrg(otsIflytekOrg);
            }
        } catch (Exception e) {
            e.printStackTrace();
            msg="error";
        }finally {
            return msg;
        }
    }
    @Transactional(rollbackFor = Exception.class)
    public String findOtsIflytekOrgUser() {
        String msg="ok";
        try {
            List<OtsIflytekOrgUser> otsIflytekOrgUserList=sysExtractDao.findOtsIflytekOrgUser();
            for (OtsIflytekOrgUser otsIflytekOrgUser:otsIflytekOrgUserList) {
                otsDataDao.insertOtsIflytekOrgUser(otsIflytekOrgUser);
            }
        } catch (Exception e) {
            e.printStackTrace();
            msg="error";
        }finally {
            return msg;
        }
    }
    @Transactional(rollbackFor = Exception.class)
    public String findOtsIflytekUser() {
        String msg="ok";
        try {
            List<OtsIflytekUser> otsIflytekUserList=sysExtractDao.findOtsIflytekUser();
            for (OtsIflytekUser otsIflytekUser:otsIflytekUserList) {
                otsDataDao.insertOtsIflytekUser(otsIflytekUser);
            }
        } catch (Exception e) {
            e.printStackTrace();
            msg="error";
        }finally {
            return msg;
        }
    }
}
